import router from '@/router'
import store from '@/store'

router.beforeEach(async(to, from, next) => {
  const token = store.getters.token
  const url = to.path
  const whiteList = ['/login', '/404']
  //  有token时，去首页
  if (token && url === '/login') {
    next('/')
  }
  //   有token时，可以去任意页面
  if (token && url !== '/login') {
    if (!store.getters.userId) {
      console.log('获取token')
      await store.dispatch('user/getUserInfo')
      console.log(store.getters.UserInfo.roles.menus)
      const res = await store.dispatch('permission/RouterFilter', store.getters.UserInfo.roles.menus)
      // 重新添加动态路由
      router.addRoutes([...res,
        { path: '*', redirect: '/404', hidden: true }
      ])
      // url => 匹配路由(空) => 获取数据  =>next(to.path) => url => 匹配路由(已经添加)
      next(to.path)
    } else {
      next()
    }
  }
  //   没有token时，可以跳转白名单
  if (!token && whiteList.includes(url)) {
    next()
  }
  //   没有token，且不在白名单，去登录
  if (!token && !whiteList.includes(url)) {
    next('/login')
  }
})
